import { useMemo } from 'react'
import type { CascadePickerOption } from './index'
import type {
  PickerValue,
  PickerColumn,
} from '../PickerView'

export function useColumnsFn(options: CascadePickerOption[]): (selected: PickerValue[]) => PickerColumn[] {
  // 最大嵌套层级数
  const depth = useMemo<number>(() => {
    let innerDepth = 0
    function traverse(innerOptions: CascadePickerOption[], currentDepth: number) {
      // 如果最大的currentDepth > innerDepth, 则将innerDepth赋值为最大的currentDepth. 其目的是筛选数组中嵌套最深的层级
      if (currentDepth > innerDepth) innerDepth = currentDepth
      const nextDepth = currentDepth + 1
      innerOptions.forEach((option) => {
        if (option.children) {
          traverse(option.children, nextDepth)
        }
      })
    }
    traverse(options, 1)
    return innerDepth
  }, [options])

  return (selected: PickerValue[]) => {
    const columns: PickerColumn[] = []
    let currentOptions = options
    let i = 0
    // eslint-disable-next-line no-constant-condition
    while (true) {
      columns.push(
        currentOptions.map((option) => ({
          label: option.label,
          value: option.value,
        })),
      )
      const x = selected[i]
      const targetOptions = currentOptions.find((option) => option.value === x)
      if (!targetOptions || !targetOptions.children) break
      currentOptions = targetOptions.children
      i++
    }
    // 动态补充columns列数
    while (i < depth - 1) {
      columns.push([])
      i++
    }

    return columns
  }
}
